#!/bin/bash

# MongoDB初始化用户脚本
# RedFire Trading System - MongoDB User Setup Script

set -e

echo "=================================================="
echo "RedFire MongoDB用户初始化开始..."
echo "Time: $(date)"
echo "=================================================="

# 等待MongoDB启动
echo "等待MongoDB服务启动..."
until mongosh --host localhost:27017 --eval "db.adminCommand('ping')" >/dev/null 2>&1; do
    echo "等待MongoDB启动中..."
    sleep 2
done

echo "MongoDB服务已启动"

# 创建管理员用户
echo "创建MongoDB管理员用户..."
mongosh --host localhost:27017 <<EOF
use admin

// 创建root管理员用户
db.createUser({
  user: "${MONGO_INITDB_ROOT_USERNAME}",
  pwd: "${MONGO_INITDB_ROOT_PASSWORD}",
  roles: [
    { role: "root", db: "admin" }
  ]
});

// 创建应用数据库
use redfire_docs

// 创建应用用户
db.createUser({
  user: "redfire_app",
  pwd: "redfire_app_mongo_2025",
  roles: [
    { role: "readWrite", db: "redfire_docs" },
    { role: "dbAdmin", db: "redfire_docs" }
  ]
});

// 创建只读用户（用于报表和分析）
db.createUser({
  user: "redfire_readonly",
  pwd: "redfire_readonly_mongo_2025",
  roles: [
    { role: "read", db: "redfire_docs" }
  ]
});

// 创建监控用户
use admin
db.createUser({
  user: "exporter",
  pwd: "redfire_exporter_mongo_2025",
  roles: [
    { role: "clusterMonitor", db: "admin" },
    { role: "read", db: "local" }
  ]
});

EOF

echo "=================================================="
echo "MongoDB用户创建完成!"
echo "数据库: redfire_docs"
echo "应用用户: redfire_app"
echo "只读用户: redfire_readonly"
echo "监控用户: exporter"
echo "=================================================="
